<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <div class="search-main flex-align-center">
          <span style="margin-right: 10px">账号状态</span>
          <el-select
            v-model="value"
            placeholder="请选择"
            style="width: 10vw; margin-right: 10px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
          <el-button
            class="btn-search"
            round
            icon="el-icon-search"
            size="medium"
            @click="initTable"
            >搜索</el-button
          >
          <el-button
            class="btn-search"
            round
            icon="el-icon-refresh"
            size="medium"
            @click="resetTable"
            >重置</el-button
          >
        </div>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dept:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >

          <el-button
            v-if="isSuperAdmin || hasPermission('system:dept:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            v-if="isSuperAdmin || hasPermission('system:dept:export')"
            @click="handleClick(null, 'export')"
            >导出</el-button
          >

          <el-input
            v-if="isSuperAdmin || hasPermission('system:dept:list')"
            v-model="input"
            placeholder="请输入项目名称/ 项目地址/ 项目简介/ 管理员/ 备注信息"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
            @change="initTable"
          >
            <el-button slot="append" icon="el-icon-search" @click="initTable"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :search-show="isSuperAdmin || hasPermission('system:dept:list')"
            :table-header="tableHeader"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :max-height="tableHeight"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        size="small"
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          sortable
          :align="item.align"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <span
              v-if="item.prop === 'deptName'"
              class="link-type"
              @click="handleClick(scope.row, 'deptName')"
              ><svg-icon
                icon-class="table-link"
                style="margin-right: 5px; width: 14px; height: 14px; fill: #165eff"
              />{{ scope.row.deptName }}</span
            >

            <span v-else-if="item.prop === 'status'" class="link-type">
              <el-switch
                v-model="scope.row.statusSwitch"
                size="small"
                :width="35"
                @change="(val) => handleChangeStatus(scope.row, val)"
            /></span>
            <span v-else>
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          size="small"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              v-if="isSuperAdmin || hasPermission('system:dept:edit')"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleClick(scope.row, 'change')"
              >编辑</el-button
            >
            <el-button
              v-if="isSuperAdmin || hasPermission('system:dept:resetPwd')"
              type="primary"
              size="mini"
              icon="el-icon-lock"
              @click="handleClick(scope.row, 'changePassword')"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <dialog-form
      v-model="dialogFormVisible"
      :rowData="rowData"
      :field="field"
      @init="initTable"
      @input="(val) => (dialogFormVisible = val)"
    />
    <ResetPwd
      v-model="dialogResetPassVisible"
      :field="field"
      :rowData="rowData"
      @input="(val) => (dialogResetPassVisible = val)"
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogForm from "../component/DialogForm";
import ResetPwd from "../component/DialogResetPwd";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import {
  deptData,
  deptDelete,
  deptChangeStatus,
  deptExport,
} from "@/api/businessmanagement";
import { queryDictData } from "@/api/systemmanagement";
export default {
  name: "BusinessList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogForm,
    ResetPwd,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      input: "",
      options: [],
      value: "",
      tableHeader: [
        {
          title: "企业名称",
          prop: "deptName",
          width: "180",
          visible: true,
          align: "left",
        },
        {
          title: "企业联系人",
          prop: "leader",
          width: "110",
          visible: true,
          align: "center",
        },
        {
          title: "手机号",
          prop: "phonenumber",
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "登录账号",
          prop: "loginName",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "项目数量",
          prop: "itemNumbers",
          width: "110",
          visible: true,
          align: "center",
        },
        {
          title: "设备数量",
          prop: "devNumbers",
          width: "110",
          visible: true,
          align: "center",
        },
        {
          title: "企业地址",
          prop: "deptAdress",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "到期时间",
          prop: "expirationDate",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "账号状态",
          prop: "status",
          width: "110",
          visible: true,
          align: "center",
        },
        {
          title: "创建时间",
          prop: "createTime",
          width: "150",
          visible: true,
          align: "center",
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      field: "",
      dialogFormVisible: false,
      dialogResetPassVisible: false,
      tableHeight: 550,
      rowData: {},
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.initTable();
  },
  methods: {
    initTable() {
      let data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        searchValue: this.input,
        status: this.value,
      };
      deptData(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.rows.map((item) => ({
            ...item,
            statusSwitch: item.status == "0" ? true : false,
          }));
          this.total = res.total;
          this.loadDictData("sys_normal_disable", "options");
        }
      });
    },
    async loadDictData(dictType, targetProperty) {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", dictType);
        // 根据接口返回的数据格式进行处理
        this[targetProperty] = [{ dictLabel: "所有", dictValue: "" }, ...data];
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      console.log(this.multipleSelection);
    },
    handleClick(row, field) {
      switch (field) {
        case "add":
          this.field = "添加企业";
          this.rowData = {};
          this.dialogFormVisible = true;
          break;
        case "change":
          this.field = "修改企业";
          this.rowData = row;
          this.dialogFormVisible = true;
          break;
        case "changePassword":
          this.field = "重置密码";
          this.rowData = row;
          this.dialogResetPassVisible = true;
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个企业吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let ids = this.multipleSelection.map((item) => item.deptId);
            deptDelete({ ids }).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.initTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          });
          break;
        case "deptName":
          let url = window.location.origin;
          window.open(
            `${url}/#/ProjectManagementRouter/ProjectList?userId=` + row.userId,
            "_blank"
          );
          break;
        case "export":
          let data = {
            searchValue: this.input,
            status: this.value,
          };
          deptExport(data).then((res) => {
            if (res.code == 0) {
              window.open(res.data.downLoadUrl, "_self");
            }
          });
          break;
        default:
          break;
      }
    },
    handleChangeStatus(row, newVal) {
      const action = newVal ? "启用" : "停用";

      this.$confirm(`确认${action}${row.deptName}账号吗?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击确定，状态已经通过 v-model 自动更新
          deptChangeStatus({
            userId: row.userId,
            status: newVal ? "0" : "1",
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: `${action}成功!`,
              });
              this.initTable();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          // 用户点击取消，恢复原来的状态
          row.statusSwitch = !newVal;
        });
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    resetTable() {
      this.value = "";
      this.initTable();
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
